import { useState } from 'react';
import { PositionOption, searchPositionsAmap, searchPositionsTianditu } from '@/servers/metro/map';
import { Select } from 'antd';
import { debounce } from 'lodash';

interface Props {
  cityCode: string;
  onSelect: (value: string, name: string) => void;
}

enum DataSource {
  TIANDITU = 'TIANDITU',
  AMAP = 'AMAP',
}
const DEFAULT_DATA_SOURCE: DataSource = DataSource.AMAP;

const PositionSearch = (props: Props) => {
  const { cityCode, onSelect } = props;
  const [options, setOptions] = useState<PositionOption[]>([]);
  const [loading, setLoading] = useState(false);

  const handleOnSearch = useMemo(() => {
    const loadOptions = async (keyword: string, source: DataSource) => {
      if (!keyword.trim()) return;

      setOptions([]);
      setLoading(true);

      if (source === DataSource.TIANDITU) {
        await searchPositionsTianditu(keyword, cityCode)
          .then((res) => setOptions(res))
          .finally(() => setLoading(false));
      } else if (source === DataSource.AMAP) {
        await searchPositionsAmap(keyword, cityCode)
          .then((res) => setOptions(res))
          .finally(() => setLoading(false));
      }
    };

    return debounce(loadOptions, 300);
  }, [cityCode]);

  return (
    <Select
      showSearch
      options={options}
      optionFilterProp="label"
      onSearch={(keyword) => handleOnSearch(keyword, DEFAULT_DATA_SOURCE)}
      onSelect={(value, option) => onSelect(value, option.name)}
      loading={loading}
      notFoundContent={loading ? '搜索中...' : '无匹配结果'}
    />
  );
};

export default PositionSearch;
